import Config from "../config"
import { async } from "./regenerator-runtime/runtime";

const regeneratorRuntime = require("../utils/regenerator-runtime/runtime")

const apiRequest = (url, data) => {
	return new Promise((resolve, reject) => {
		url = `${Config.apiUrl + url}`
		const method = "POST"
    //header = { 'content-type': 'application/x-www-form-urlencoded' }
    console.log(data);
		wx.request({
			url,
			method,
			data,
			// header,
			success: res => {
				// console.log(res)
				if(res.statusCode == 200) {
					resolve(res.data)
				} else {
					reject({statusCode: res.statusCode})
				}
			},
			fail: err => {
				// console.error(err)
				reject(err)
			}
		})
	})
}

const apiRequestMethod = (method, url, data) => {
  return new Promise((resolve, reject) => {
    url = `${Config.apiUrl + url}`
    //header = { 'content-type': 'application/x-www-form-urlencoded' }
    console.log(data);
    wx.request({
      url,
      method,
      data,
      // header,
      success: res => {
        // console.log(res)
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject({ statusCode: res.statusCode })
        }
      },
      fail: err => {
        // console.error(err)
        reject(err)
      }
    })
  })
}

function parseParams(data) {
  try {
    var tempArr = [];
    for (var i in data) {
      var key = encodeURIComponent(i);
      var value = encodeURIComponent(data[i]);
      tempArr.push(key + '=' + value);
    }
    var urlParamsStr = tempArr.join('&');
    return urlParamsStr;
  } catch (err) {
    return '';
  }
}

const apiRequestGet = (url, data) => {
	return new Promise((resolve, reject) => {
		const method = "Get",
			header = { 'content-type': 'application/x-www-form-urlencoded' }
      //url = `${Config.apiUrl + url}` + "?" + parseParams(data)
    url = `${Config.apiUrl + url}` + data;
		wx.request({
			url,
			method,
			header,
			success: res => {
				// console.log(res)
				if (res.statusCode == 200) {
					resolve(res.data)
				} else {
					reject({ statusCode: res.statusCode })
				}
			},
			fail: err => {
				// console.error(err)
				reject(err)
			}
		})
	})
}

const Api = {
  setSetting: async (openid, custom, arg) => {
    const status = "select"
    let data = {}
    if(custom==0){
      data={
        openid, custom, days:arg[0], music:arg[1]
      }
    }else{
      data = {
        openid, custom, type: arg[0], music_length: arg[1], music:arg[2]
      }
    }
    return await apiRequest("setting/set",data)
  },
	gotoAuth: () => {
		const route = getCurrentPages()[0].route
		const url = "/pages/login/login?route="+route
		wx.redirectTo({url})
	},
	Login: () => {
		return new Promise((resolve, reject) => {
			wx.login({
				success: async res => {
					const {code} = res
					try {
            const result = await apiRequestGet("user/code2session/", code)
						if(result.status == 0) {
							wx.setStorageSync("openid", result.data.openid)
							resolve(result.data)
						} else {
							reject(result)
						}
					} catch (ex) {
						reject(ex)
					}
				},
				fail: err => {
					wx.showModal({
						title: '提示',
						content: '网络故障，请稍后重试',
					})
					reject(err)
				}
			})
		})
	},
	getUserInfo: () => {
		return new Promise((resolve, reject) => {
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            console.log('授权：yes')
            wx.getUserInfo({
              lang: "zh_CN",
              success: res => {
                console.log(res)
                wx.setStorageSync("userInfo", res.userInfo);
                resolve([res.userInfo, res.encryptedData, res.iv])
              },
              fail: error => {
                console.log(error)
                resolve([false,"",""])
              }
            })
          }else{
            console.log("未授权")
            resolve([false, "", ""])
          }
        },
        fail: error => {
          console.log(error)
          resolve([false, "", ""])
        }
      })
		})
	},
	/**
	 * 获取解密数据
	 */
	decryptData: async (openid,encryptedData, iv)=>{
    const data = {openid,encryptedData,iv}
    return await apiRequest("user/decrypt", data)
	},
  //收集formid
  collectionId:(openid,formid)=>{
    apiRequest("cform", {
      status: 'add',
      openid: openid,
      formid: formid
    })
  },
	
	uploadImage: async (filePath, openid) => {
		return new Promise((resolve, reject) => {
      const formData = { openid, filePath }
			wx.uploadFile({
        url: `${Config.apiUrl}image/upload`,
				filePath,
				name: 'file',
				formData,
				success: res => {
					const data = JSON.parse(res.data)
					resolve(data)
				},
				fail: error => {
					reject(error)
				}
			})
		})
	},
	// uploadVideo: async (filePath, openid, type = "page", width, height) => {
	// return new Promise((resolve, reject) => {
	// 	const status = "upload", formData = { status, openid, type, width, height}
	// 	console.log({
	// 	url: `${Config.apiUrl}video`, filePath, name: 'file', status, openid, type, width, height})
	// 	wx.uploadFile({
	// 	url: `${Config.apiUrl}video`,
	// 	filePath,
	// 	name: 'file',
	// 	formData,
	// 	success: res => {
	// 		const data = JSON.parse(res.data)
	// 		resolve(data)
	// 	},
	// 	fail: error => {
	// 		reject(error)
	// 	}
	// 	})
	// })
	// },
  setActivity: async formData => {
    const res = await apiRequest("post/add", formData)
    return res;
	},
  getActivityePage: async (page, openid, keyword, sort_field, sort_direction) => {
    const res = await apiRequest("post/page", { page, openid, keyword, sort_field, sort_direction})
    return res;
	},
  getmyActivityePage: async (type, openid, page, sort_field, sort_direction) => {
    const res = await apiRequest("post/my", { page, openid, type, sort_field, sort_direction })
    return res;
  },
  getActivityebyId: async (openid,id) => {
    const res = await apiRequest("post/get/", { openid, id })
    return res;
  },
  getReply: async(pid)=>{
    const res = await apiRequestGet("post/reply/", pid)
    return res;
  },
  postLike: async (openid,pid)=>{
    const res = await apiRequest("post/like", {openid,pid})
    return res;
  },
  postReply: async (openid, pid, content)=>{
    const res = await apiRequest("post/reply", { openid, pid, content})
    return res;
  },
  deleteReply: async (openid, id) => {
    const res = await apiRequestMethod("DELETE","post/reply", { openid, id})
    return res;
  },
  deleteActivity: async (openid, id) => {
    const res = await apiRequestMethod("DELETE", "post/del", { openid, id })
    return res;
  },
  getAllSetting: async (openid) => {
    const res = await apiRequest("setting/all", { openid})
    return res;
  },
  getSettingById: async (openid,id) => {
    const res = await apiRequest("setting/get", { openid,id})
    return res;
  },
  getMusic: async (openid, id, date) => {
    const res = await apiRequest("setting/music", { openid, id, date})
    return res;
  },
  settingcomplete: async (openid, id, date) => {
    const res = await apiRequest("setting/complete", { openid, id, date })
    return res;
  },
}
export default Api